package mapspinner.persistence.rmi;

import java.rmi.Naming;
import java.rmi.Remote;
import java.rmi.server.UnicastRemoteObject;

import mapspinner.TerrainKey;
import mapspinner.persistence.TerrainPersistence;
import mapspinner.persistence.datatypes.TerrainData;
import mapspinner.persistence.datatypes.TerrainSettings;

public class TerrainClientImpl implements Remote, TerrainPersistence {
	private final String ipAdress = "localhost";
	/** The Chronus remote server */
	private TerrainServer server;

	public TerrainClientImpl() {
		try {
			initRMI();
		} catch (final Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public TerrainSettings getSettings(final String directory) throws Exception {
		return server.getSettings(directory);
	}

	public TerrainData getTerrainData(final TerrainKey key,
			final String directory) throws Exception {
		return server.getTerrainData(key, directory);
	}

	public void initRMI() throws Exception {
		UnicastRemoteObject.exportObject(this);

		final String serverName = "rmi://" + ipAdress + ":6667"
				+ "/MapPersistence";

		System.out.println("Looking up rmi server at: " + serverName);

		server = (TerrainServer) Naming.lookup(serverName);
	}

	@Override
	public void setSettings(final String directory,
			final TerrainSettings settings) throws Exception {
		server.setSettings(directory, settings);
	}

	public void setTerrainData(final TerrainKey key, final TerrainData mapData,
			final String directory) throws Exception {
		server.setTerrainData(key, mapData, directory);
	}

}
